import React, { useEffect, useState } from 'react'
import './index.scss'
import T from 'prop-types'
import ReactDOM from 'react-dom'
export default function Message(props) {
  let { mesText, time = 4000 } = props
  const [showMes, setShowMes] = useState('block')
  let timer
  useEffect(() => {
      show()
  },[])
  const show = () => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      hide()
    }, time)
  }
  const hide = () => {
    setShowMes('none')
  }
  return (
    <div className="message" style={{ display: showMes }}>
      {mesText}
    </div>
  )
}
Message.propTypes = {
  mesText: T.string,
  time: T.number,
}
export function message(mesText,time) {
    const div = document.createElement('div')
    document.body.appendChild(div)

    ReactDOM.render(<Message mesText={mesText} time={time}></Message>, div)
    function close() {
      ReactDOM.unmountComponentAtNode(div)
      if (div && div.parentNode) {
        div.parentNode.removeChild(div)
      }
    }
    setTimeout(() => {
      close()
    }, 1500)
}